﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CefSharp;
using CefSharp.WinForms;
using System.Windows.Forms;
using SAM.Framework.CefSharp.UI;
using SAM.Framework.UserBrowser;

namespace SAM.Framework.CefSharpTest
{
    public partial class Form1 : Form
    {
        private IUserBrowser userBrowser;
        private Test test;
        private delegate void VisibleDelegate();
        public Form1()
        {
            InitializeComponent();
            var userWebBrowser = new UserWebBrowser(System.IO.Directory.GetCurrentDirectory() + "/index.html");
            this.userBrowser = userWebBrowser;
            // userBrowser.Load(System.IO.Directory.GetCurrentDirectory() + "/index.html");
            userWebBrowser.Dock = DockStyle.Fill; 
            this.userBrowser.OnFrameLoadEnd += UserBrowser_OnFrameLoadEnd;
            this.test = new Test()
            {
                Name = "Name"
            };
            this.userBrowser.RegisterObject("test", this.test);
        }

        private void UserBrowser_OnFrameLoadEnd(object sender, EventArgs e)
        {
            this.userBrowser.ExecuteJavaScriptAsync("document.body.style.background='red';");
            return;
            if (this.InvokeRequired)
            {
                this.Invoke(new VisibleDelegate(VisiblePanel));
            }
        }

        private void VisiblePanel()
        {
            //延迟显示，解决刷新的问题
            this.panel1.Visible = true;
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            this.userBrowser.Dispose();
            base.OnFormClosed(e);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.userBrowser.Load("http://www.baidu.com");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.test.Name = "button2";
            this.userBrowser.ExecuteJavaScriptAsync("refresh();");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            this.test.Name = "button3";
            this.userBrowser.ExecuteJavaScriptAsync("refresh(" + Newtonsoft.Json.JsonConvert.SerializeObject(this.test) + ");");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.panel1.Controls.Add(this.userBrowser as UserControl);
            //this.panel1.Visible = false;
        }
    }
    [Serializable]
    public class Test : TransportObject
    {
        public string Name { get; set; }
    }

}
